import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      // home:  Echo(
      //   text: "hello world",
      // ),
      home: ContextRoute(),
      // home: CounterWidget(),
    );
  }
}

class Echo extends StatelessWidget {
  final String text;

  final Color backgroundColor;

  const Echo({Key key, @required this.text, this.backgroundColor: Colors.grey})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        color: this.backgroundColor,
        child: Text(this.text),
      ),
    );
  }
}

// 通过 context 上下文获取UI树上的其他 widget
class ContextRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Context测试"),
      ),
      body: Container(
        child: Builder(
          builder: (context) {
            // 在 widget 树中向上查找最近的父级 ‘Scaffold‘ widget
            Scaffold scaffold =
                context.findAncestorWidgetOfExactType<Scaffold>();
            // 直接返回 AppBar 的标题
            return (scaffold.appBar as AppBar).title;
          },
        ),
      ),
    );
  }
}

// state 生命周期
class CounterWidget extends StatefulWidget {
  final int intValue;

  CounterWidget({Key key, this.intValue: 0});

  @override
  State<StatefulWidget> createState() {
    return _CounterWidgetState();
  }
}

class _CounterWidgetState extends State<CounterWidget> {
  int _counter;

  @override
  void initState() {
    super.initState();
    // 初始化
    _counter = widget.intValue;
    print("initState");
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    return Scaffold(
      body: Center(
        child: FlatButton(
          child: Text('$_counter'),
          onPressed: () => this.setState(() => ++_counter),
        ),
      ),
    );
  }

  @override
  void didUpdateWidget(covariant CounterWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("didUpdateWidget");
  }

  @override
  void deactivate() {
    super.deactivate();
    print("deactivate");
  }

  @override
  void dispose() {
    super.dispose();
    print("dispose");
  }

  @override
  void reassemble() {
    super.reassemble();
    print("reassemble");
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("didChangeDependencies");
  }

}
